package com.lcxw.hxzbcommon.common;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradeAppPayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradeAppPayRequest;
import com.alipay.api.response.AlipayTradeAppPayResponse;
import com.lcxw.hxzbcommon.entity.CommonBean;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AlipayUtil {

    private String appId = CommonBean.ALIPAY_APPID;
    private String charset = "UTF-8";
    private String alipay_Public_Key = CommonBean.ALIPAY_PUBLIC_KEY;
    private String app_Private_Key = CommonBean.ALIPAY_APP_PRIVATE_KEY;
    private String alipay_NotifyUrl = CommonBean.ALIPAY_NOTIFY_URL;
    private String alipay_timeoutExpress = CommonBean.ALIPAY_TIMEOUT_EXPRESS;

    public String createOrderInfo(String body, String subject, String outTradeNo,
        String totalAmount, String productCode) {

        //实例化客户端
        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do",
            appId, app_Private_Key, "json", charset, alipay_Public_Key, "RSA2");
        //实例化具体API对应的request类,类名称和接口名称对应,当前调用接口名称：alipay.trade.app.pay
        AlipayTradeAppPayRequest request = new AlipayTradeAppPayRequest();
        //SDK已经封装掉了公共参数，这里只需要传入业务参数。以下方法为sdk的model入参方式(model和biz_content同时存在的情况下取biz_content)。
        AlipayTradeAppPayModel model = new AlipayTradeAppPayModel();
        model.setBody(body);
        model.setSubject(subject);
        model.setOutTradeNo(outTradeNo);
        model.setTimeoutExpress(alipay_timeoutExpress);
        model.setTotalAmount(totalAmount);
        model.setProductCode(productCode);
        request.setBizModel(model);
        request.setNotifyUrl(alipay_NotifyUrl);

        AlipayTradeAppPayResponse response;
        try {
            //这里和普通的接口调用不同，使用的是sdkExecute
            response = alipayClient.sdkExecute(request);
        } catch (AlipayApiException e) {
            e.printStackTrace();
            log.error("调用支付宝sdk的sdkExecute失败，创建支付信息失败");
            return null;
        }
        //就是orderString 可以直接给客户端请求，无需再做处理。
        return response.getBody();
    }

    /**
     * 支付宝异步通知解析验签
     * @param request request
     * @param response response
     * @return JsonObject 该对象请参照支付宝异步通知参数  https://opendocs.alipay.com/open/203/105286
     */
    public JSONObject dealAlipayNotify(HttpServletRequest request, HttpServletResponse response) {


        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<>();
        Map requestParams = request.getParameterMap();
        for (Iterator iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                    : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用。
            //valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        try {
            boolean flag = AlipaySignature
                .rsaCheckV1(params, CommonBean.ALIPAY_PUBLIC_KEY, "UTF-8", "RSA2");

            if (flag) {
                PrintWriter writer = response.getWriter();
                writer.println("success");
                writer.flush();
                return JSONObject.parseObject(JSON.toJSONString(params));
            }

        } catch (AlipayApiException | IOException e) {
            e.printStackTrace();
        }
        return null;

    }

    public static void main(String[] args) {
        AlipayUtil alipayUtil = new AlipayUtil();
        System.out.println(alipayUtil
            .createOrderInfo("测试数据", "约玩派对支付测试", "outTradeNo2020050605", "0.01",
                "QUICK_MSECURITY_PAY"));
    }

}
